package com.zhenyi.xiaohuoche.admin;

import java.math.BigDecimal;

import com.jfinal.aop.Before;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.xhc.common.model.XhcPresent;
import com.zhenyi.xhc.core.OrderUtils;
import com.zhenyi.xhc.core.XHCAuthInterceptor;
import com.zhenyi.xhc.core.XHCController;

@Before(XHCAuthInterceptor.class)
public class AdminPresentController extends XHCController {

	@Override
	public void list() {
		SqlPara sqlPara = Db.getSqlPara("FindPresents");
		Page<XhcPresent> pages = XhcPresent.dao.paginate(getPage(), PAGE_SIZE, sqlPara);
		renderPage(pages);
	}

	@Override
	public void delete() {
		Long id = getParaToLong("id");
		if (id == null) {
			renderFailure("id is null");
			return;
		}
		XhcPresent info = XhcPresent.dao.findById(id);
		if (info == null) {
			renderFailure("info is null");
			return;
		}
		info.setFlag(1);
		Boolean flag = info.update();
		if (flag) {
			renderSuccess();
		} else {
			renderMsg("删除失败");
			return;
		}
	}

	@Override
	public void info() {
		Long id = getParaToLong("id");
		XhcPresent info = id == null ? new XhcPresent() : XhcPresent.dao.findById(id);
		renderResult(info);
	}

	@Override
	public void submit() {
		Long id = getParaToLong("id");
		String title = getPara("title");
		String desc = getPara("desc");
		String cover = getPara("cover");
		String images = getPara("images");
		Integer count = getParaToInt("count");
		BigDecimal price = new BigDecimal(getPara("price", "0"));
		XhcPresent info = id == null ? new XhcPresent() : XhcPresent.dao.findById(id);
		info.setTitle(title);
		info.setDesc(desc);
		info.setCover(cover);
		info.setImages(images);
		info.setCount(count);
		info.setPrice(price);
		Boolean flag = info.updateIfExist();
		if (flag) {
			renderSuccess();
		} else {
			renderFailure("保存失败");
			return;
		}
	}

	/**
	 * 礼物退款
	 */
	@Before(Tx.class)
	public void refund() {
		// Long id = getParaToLong("id");
		String no = getPara("no"); // 2018042318092279716a
		if (StrKit.isBlank(no)) {
			System.out.println("no is null");
			renderFailure("no error");
			return;
		}
		Long id = OrderUtils.decode(no);
		if (id == null) {
			System.out.println("id is null");
			renderFailure();
			return;
		}
		orderUtils.refundPresent(this, id);
	}
}
